﻿package scrn;


import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.swing.DefaultListModel;
import javax.swing.SwingUtilities;

import cont.*;

import core.*;

import media.*;


// ========================================== Форма поиска и добавления приватов
public class AddOne extends javax.swing.JFrame {

// =================================================================== Константы
private static final long serialVersionUID = 1L;

private static final int BUT_FIND_FIND = 0; // Режим поиска
private static final int BUT_FIND_WAIT = 1; // Режим ожидания результатов
private static final int BUT_FIND_ADD = 2; // Режим добавления контакта

// ================================================================== Переменные
DefaultListModel listModel;
private ContOne[] conts; // Текущий список контактов
private int butFindMode = BUT_FIND_FIND; // Режим работы кнопки поиска


// =============================================================== Инициализация
/** Creates new form AddOne */
public AddOne() {

	BufferedImage img = Pic.loadImage("icon.png");

	if (img != null) {
		this.setIconImage(img);
		img = null;
	}


	initComponents();
}


//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

	jScrollPane4 = new javax.swing.JScrollPane();
	jTextPane2 = new javax.swing.JTextPane();
	panTop = new javax.swing.JPanel();
	textFind = new javax.swing.JLabel();
	textNick = new javax.swing.JLabel();
	tfNick = new javax.swing.JTextField();
	panMid = new javax.swing.JPanel();
	panCard0 = new javax.swing.JPanel();
	labHelp = new javax.swing.JLabel();
	panCard1 = new javax.swing.JPanel();
	jScrollPane1 = new javax.swing.JScrollPane();
	listOne = new javax.swing.JList();
	panBot = new javax.swing.JPanel();
	butFind = new javax.swing.JButton();
	butCancel = new javax.swing.JButton();

	jScrollPane4.setViewportView(jTextPane2);

	setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
	setTitle("\u041c\u043e\u043b\u0427\u0410\u0422.\u041a\u043e\u043d\u0442\u0430\u043a\u0442\u044b");
	addWindowListener(new java.awt.event.WindowAdapter() {

		public void windowClosing(java.awt.event.WindowEvent evt) {

			formWindowClosing(evt);
		}
	});
	getContentPane()
			.setLayout(
					new javax.swing.BoxLayout(getContentPane(),
							javax.swing.BoxLayout.Y_AXIS));

	panTop.setAlignmentY(1.0F);
	panTop.setMaximumSize(new java.awt.Dimension(2048, 70));
	panTop.setMinimumSize(new java.awt.Dimension(180, 70));
	panTop.setPreferredSize(new java.awt.Dimension(240, 70));

	textFind.setFont(new java.awt.Font("Tahoma", 1, 14));
	textFind.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
	textFind
			.setText("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043a\u043e\u043d\u0442\u0430\u043a\u0442\u0430");
	textFind.setAlignmentX(0.5F);
	textFind.setFocusable(false);
	textFind.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

	textNick
			.setText("<html><strong>\u041d\u0438\u043a (\u0438\u043b\u0438 \u0447\u0430\u0441\u0442\u044c):</strong></html>");
	textNick.setMaximumSize(new java.awt.Dimension(2048, 2048));
	textNick.setMinimumSize(new java.awt.Dimension(100, 14));
	textNick.setPreferredSize(new java.awt.Dimension(100, 14));

	tfNick.setMaximumSize(new java.awt.Dimension(2048, 2048));
	tfNick.setMinimumSize(new java.awt.Dimension(10, 20));
	tfNick.addFocusListener(new java.awt.event.FocusAdapter() {

		public void focusGained(java.awt.event.FocusEvent evt) {

			tfNickFocusGained(evt);
		}
	});
	tfNick.addKeyListener(new java.awt.event.KeyAdapter() {

		public void keyPressed(java.awt.event.KeyEvent evt) {

			tfNickKeyPressed(evt);
		}
	});

	javax.swing.GroupLayout panTopLayout = new javax.swing.GroupLayout(panTop);
	panTop.setLayout(panTopLayout);
	panTopLayout.setHorizontalGroup(panTopLayout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panTopLayout.createSequentialGroup().addContainerGap().addGroup(
					panTopLayout.createParallelGroup(
							javax.swing.GroupLayout.Alignment.LEADING).addComponent(textFind,
							javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
							.addGroup(
									panTopLayout.createSequentialGroup().addComponent(textNick,
											javax.swing.GroupLayout.PREFERRED_SIZE,
											javax.swing.GroupLayout.DEFAULT_SIZE,
											javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(
											javax.swing.LayoutStyle.ComponentPlacement.RELATED)
											.addComponent(tfNick,
													javax.swing.GroupLayout.DEFAULT_SIZE, 105,
													Short.MAX_VALUE))).addContainerGap()));
	panTopLayout.setVerticalGroup(panTopLayout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panTopLayout.createSequentialGroup().addContainerGap().addComponent(
					textFind).addGap(18, 18, 18).addGroup(
					panTopLayout.createParallelGroup(
							javax.swing.GroupLayout.Alignment.BASELINE).addComponent(
							textNick, javax.swing.GroupLayout.PREFERRED_SIZE,
							javax.swing.GroupLayout.DEFAULT_SIZE,
							javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(tfNick,
							javax.swing.GroupLayout.PREFERRED_SIZE,
							javax.swing.GroupLayout.DEFAULT_SIZE,
							javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap(
					javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

	getContentPane().add(panTop);

	panMid.setAlignmentY(0.0F);
	panMid.setMaximumSize(new java.awt.Dimension(2048, 2048));
	panMid.setPreferredSize(new java.awt.Dimension(240, 240));
	panMid.setLayout(new java.awt.CardLayout());

	panCard0.setMaximumSize(new java.awt.Dimension(2048, 2048));
	panCard0.setMinimumSize(new java.awt.Dimension(0, 0));
	panCard0.setPreferredSize(new java.awt.Dimension(240, 250));

	labHelp.setForeground(new java.awt.Color(102, 102, 102));
	labHelp
			.setText("<html>\n<body>\n<p><strong>\u041f\u043e\u0434\u0441\u043a\u0430\u0437\u043a\u0430:</strong></p>\n<p>\u041d\u0435 \u043e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u0432\u0432\u043e\u0434\u0438\u0442\u044c \u043d\u0438\u043a \u0446\u0435\u043b\u0438\u043a\u043e\u043c.</p>\n<p>\u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0447\u0442\u043e\u0431\u044b \u043d\u0430\u0439\u0442\u0438 \u043d\u0438\u043a <pre><strong>\\/it@min|{@</strong></pre>\u043c\u043e\u0436\u043d\u043e \u043f\u0438\u0441\u0430\u0442\u044c <strong>\\/it@</strong>, <strong>it@min</strong>, \u0438\u043b\u0438 \u0434\u0430\u0436\u0435 <strong>min</strong>, - \u043d\u0438\u043a \u0431\u0443\u0434\u0435\u0442 \u043d\u0430\u0439\u0434\u0435\u043d.</p>\n</body>\n</html>");
	labHelp.setVerticalAlignment(javax.swing.SwingConstants.TOP);
	labHelp.setMaximumSize(new java.awt.Dimension(2048, 2048));
	labHelp.setPreferredSize(new java.awt.Dimension(200, 250));

	javax.swing.GroupLayout panCard0Layout = new javax.swing.GroupLayout(panCard0);
	panCard0.setLayout(panCard0Layout);
	panCard0Layout.setHorizontalGroup(panCard0Layout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panCard0Layout.createSequentialGroup().addContainerGap().addComponent(
					labHelp, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
					.addContainerGap()));
	panCard0Layout.setVerticalGroup(panCard0Layout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panCard0Layout.createSequentialGroup().addContainerGap().addComponent(
					labHelp, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
					.addContainerGap()));

	panMid.add(panCard0, "card0");

	panCard1.setMaximumSize(new java.awt.Dimension(2048, 2048));
	panCard1.setMinimumSize(new java.awt.Dimension(100, 100));
	panCard1.setPreferredSize(new java.awt.Dimension(240, 260));

	listOne.addFocusListener(new java.awt.event.FocusAdapter() {

		public void focusGained(java.awt.event.FocusEvent evt) {

			listOneFocusGained(evt);
		}
	});
	jScrollPane1.setViewportView(listOne);

	javax.swing.GroupLayout panCard1Layout = new javax.swing.GroupLayout(panCard1);
	panCard1.setLayout(panCard1Layout);
	panCard1Layout.setHorizontalGroup(panCard1Layout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panCard1Layout.createSequentialGroup().addContainerGap().addComponent(
					jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209,
					Short.MAX_VALUE).addContainerGap()));
	panCard1Layout.setVerticalGroup(panCard1Layout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panCard1Layout.createSequentialGroup().addContainerGap().addComponent(
					jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237,
					Short.MAX_VALUE)));

	panMid.add(panCard1, "card1");

	getContentPane().add(panMid);

	panBot.setAlignmentY(1.0F);
	panBot.setMaximumSize(new java.awt.Dimension(2048, 64));
	panBot.setMinimumSize(new java.awt.Dimension(100, 40));
	panBot.setPreferredSize(new java.awt.Dimension(240, 56));
	panBot.setRequestFocusEnabled(false);

	butFind
			.setText("<html><strong>\u0418\u0441\u043a\u0430\u0442\u044c</strong></html>");
	butFind.setMaximumSize(new java.awt.Dimension(70, 30));
	butFind.addActionListener(new java.awt.event.ActionListener() {

		public void actionPerformed(java.awt.event.ActionEvent evt) {

			butFindActionPerformed(evt);
		}
	});

	butCancel.setText("\u041e\u0442\u043c\u0435\u043d\u0430");
	butCancel.addActionListener(new java.awt.event.ActionListener() {

		public void actionPerformed(java.awt.event.ActionEvent evt) {

			butCancelActionPerformed(evt);
		}
	});

	javax.swing.GroupLayout panBotLayout = new javax.swing.GroupLayout(panBot);
	panBot.setLayout(panBotLayout);
	panBotLayout.setHorizontalGroup(panBotLayout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			panBotLayout.createSequentialGroup().addContainerGap().addComponent(
					butFind, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
					.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
					.addComponent(butCancel).addContainerGap()));
	panBotLayout.setVerticalGroup(panBotLayout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			javax.swing.GroupLayout.Alignment.TRAILING,
			panBotLayout.createSequentialGroup().addContainerGap(13, Short.MAX_VALUE)
					.addGroup(
							panBotLayout.createParallelGroup(
									javax.swing.GroupLayout.Alignment.BASELINE).addComponent(
									butCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 32,
									javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(butFind,
									javax.swing.GroupLayout.PREFERRED_SIZE, 32,
									javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));


	panBotLayout.linkSize(javax.swing.SwingConstants.VERTICAL,
			new java.awt.Component[] { butCancel, butFind });


	getContentPane().add(panBot);

	pack();
}// </editor-fold>
//GEN-END:initComponents


private void listOneFocusGained(java.awt.event.FocusEvent evt) {

	if (listModel.getSize() > 0) { // Есть результаты поиска
		setButFindMode(AddOne.BUT_FIND_ADD);
	}
}


private void setButFindMode(int butFindMode) {

	this.butFindMode = butFindMode;
	switch (butFindMode) {
		case AddOne.BUT_FIND_FIND: // Сейчас - режим поиска
			butFind.setText("<html><strong>Искать</strong></html>");
			butFind.setEnabled(true);
			break;
		case AddOne.BUT_FIND_ADD: // Режим добавления выделенного контакта
			butFind.setText("<html><strong>Добавить</strong></html>");
			butFind.setEnabled(true);
			butFind.requestFocusInWindow();
			break;
		case AddOne.BUT_FIND_WAIT: // Сейчас - ждем
			butFind.setEnabled(false);
			butFind.setText("Идет поиск...");
			break;
	}
}


private void tfNickFocusGained(java.awt.event.FocusEvent evt) {

	switch (butFindMode) {
		case AddOne.BUT_FIND_FIND: // Сейчас - режим поиска
			break;
		case AddOne.BUT_FIND_ADD: // Режим добавления выделенного контакта
			setButFindMode(BUT_FIND_FIND);
			break;
		case AddOne.BUT_FIND_WAIT: // Сейчас - ждем
			break;
	}
}


private void formWindowClosing(java.awt.event.WindowEvent evt) {

	butCancelActionPerformed(null);
}


private void butCancelActionPerformed(java.awt.event.ActionEvent evt) {

	Man.scrMan.addOne = null;
	this.dispose();
}


private void tfNickKeyPressed(java.awt.event.KeyEvent evt) {

	int code = evt.getKeyCode();

	if (code == KeyEvent.VK_ENTER) {
		evt.consume();
		butFindActionPerformed(null);
	}
}


private void butFindActionPerformed(java.awt.event.ActionEvent evt) {

	switch (butFindMode) {
		case AddOne.BUT_FIND_FIND: // Сейчас - режим поиска
			int maxResults = Setting.maxFind;

			try {
				Man.ioMan.outFindOne(tfNick.getText(), maxResults);
			} catch (Exception e) {
				Mess.err("AddOne.butFindActionPerformed",
						"Не удалось отправить запрос", e);
			}

			setButFindMode(BUT_FIND_WAIT);
			break;
		case AddOne.BUT_FIND_ADD: // Режим добавления выделенного контакта
			int ind = listOne.getSelectedIndex();
			try {
				Man.ioMan.outAddCont(Cont.ONE, ind);
			} catch (Exception e) {
				Mess.err("AddRoom.commandAction", "Не удается отправить запрос");
			}
			butCancelActionPerformed(evt);
			break;
		case AddOne.BUT_FIND_WAIT: // Сейчас - ждем
			break;
	}
}


// =================================================== Добавить комнату в список
private void add(ContOne one) {

	String gendImage; // Картинка контакта
	String text; // Краткое описание

	switch (one.info.gender) {
		case Cont.G_MALE:
			gendImage = "one_bl.png";
			break;
		case Cont.G_FEMALE:
			gendImage = "one_pi.png";
			break;
		default:
			gendImage = "one_gr.png";
	}

	URL url = Pic.getURL(gendImage);

	text = "<html><img src='" + url + "' align='center' /> <strong>" + one.name
			+ "</strong>";

	if (one.info.descr != null) {
		text += "<br />" + one.info.descr;
	}

	text += "</html>";

	//	Mess.m("AddOne.add", "text='" + text + "'");
	listModel.addElement(text);
}


// ========================================== Получен результат поиска контактов
public void inFind(int contType, ContOne[] contsList) {

	Mess.m("AddOne.inFind", "Отображаю список контактов");

	this.conts = contsList;

	if (SwingUtilities.isEventDispatchThread()) {
		Mess.err("AddOne.inFind", "Среда EDT!");
	} else {

		try {
			SwingUtilities.invokeAndWait(new Runnable() {

				public void run() {

					listModel = new DefaultListModel();
					listModel.ensureCapacity(conts.length);
					listOne.setModel(listModel);

					for (int q = 0; q < conts.length; ++q) {
						add(conts[q]);
					}

					Container contentPane = panMid;
					CardLayout cardLayout = (CardLayout) (contentPane.getLayout());
					cardLayout.show(contentPane, "card1");

					if (conts.length > 0) {
						listOne.setSelectedIndex(0);
						setButFindMode(AddOne.BUT_FIND_ADD);
					} else {
						setButFindMode(AddOne.BUT_FIND_FIND);
					}

					conts = null;
				}
			});
		} catch (Exception e) {
			Mess.err("AddOne.inFind", e);
		}
	}

}

//GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton butCancel;
private javax.swing.JButton butFind;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTextPane jTextPane2;
private javax.swing.JLabel labHelp;
private javax.swing.JList listOne;
private javax.swing.JPanel panBot;
private javax.swing.JPanel panCard0;
private javax.swing.JPanel panCard1;
private javax.swing.JPanel panMid;
private javax.swing.JPanel panTop;
private javax.swing.JLabel textFind;
private javax.swing.JLabel textNick;
private javax.swing.JTextField tfNick;
// End of variables declaration//GEN-END:variables

}